<template>
  <view class="shop-page">
    <!-- 顶部店铺信息 -->
    <view class="shop-header" v-if="shopInfo && shopInfo.id">
      <view class="shop-cover">
        <image class="shop-logo" :src="shopInfo.shopLogo" mode="aspectFill"></image>

      </view>
      <view class="shop-details">
        <view class="shop-title">
          <text class="shop-name">{{ shopInfo.shopName || '-' }}</text>
          <view class="shop-status" v-if="shopInfo.shopStatus === 1">
            <text class="status-text">营业中</text>
          </view>
        </view>
        <view class="shop-info-item">
          <u-icon name="account" color="#ffffff" size="26"></u-icon>
          <text class="info-text">{{ shopInfo.shopOwner || '-' }}</text>
        </view>
        <view class="shop-info-item" @click="callPhone">
          <u-icon name="phone" color="#ffffff" size="26"></u-icon>
          <text class="info-text">{{ shopInfo.tel || '-' }}</text>
        </view>
        <view class="shop-info-item" @click="goToMap">
          <u-icon name="map" color="#ffffff" size="26"></u-icon>
          <text class="info-text">{{ shopInfo.shopAddress || '-' }}</text>
          <u-icon name="arrow-right" color="#c0c4cc" size="24"></u-icon>
        </view>
        <view class="shop-intro" v-if="shopInfo.intro">
          <text class="intro-text">{{ shopInfo.intro }}</text>
        </view>
      </view>
    </view>

    <!-- 顶部占位，防抖 -->
    <view v-else class="shop-header placeholder"></view>

    <!-- Tab 切换 -->
    <view class="tabs-wrap">
      <u-tabs :list="tabs" :current="activeTab" @change="onTabChange" lineColor="#4a90e2"></u-tabs>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-scroll" scroll-y @scrolltolower="onReachListBottom">
      <!-- 商品列表 -->
      <view v-if="activeTab === 0" class="goods-list">
        <block v-if="goodsList.length > 0">
          <view class="goods-item" v-for="(item, idx) in goodsList" :key="idx"
                @click="goGoodsDetail(item)">
            <image class="goods-cover" :src="item.pic" mode="aspectFill"></image>
            <view class="goods-info">
              <text class="goods-name">{{ item.prodName || '-' }}</text>
              <text class="goods-brief">{{ item.brief || '暂无商品描述' }}</text>
              <view class="goods-meta">
                <text class="meta">单位：{{ item.units || '-' }}</text>
                <text class="meta">销量：{{ (item.soldNum || 0) }}</text>
              </view>
              <view class="goods-bottom">
                <text class="price">¥{{ formatPrice(item.price) }}</text>
                <text class="stock">库存：{{ item.totalStocks || 0 }}</text>
              </view>
            </view>
          </view>
          <view class="load-more" v-if="hasMore">
            <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
          </view>
          <view class="no-more" v-else>
            <text class="no-more-text">没有更多商品了</text>
          </view>
        </block>
        <view class="empty" v-else>
          <text class="empty-text">该商家暂无上架商品</text>
        </view>
      </view>

      <!-- 评价列表 -->
      <view v-else class="reviews-wrap">
        <block v-if="commList.length > 0">
          <view class="review-card" v-for="(item, idx) in commList" :key="idx">
            <!-- 用户头部信息 -->
            <view class="review-header">
              <view class="user-info">
                <view class="user-avatar">
                  <text class="avatar-text">{{ (item.userId_dictText || '匿名用户').charAt(0) }}</text>
                </view>
                <view class="user-details">
                  <text class="user-name">{{ item.userId_dictText || '匿名用户' }}</text>
                  <text class="review-date">{{ formatReviewTime(item.createTime) }}</text>
                </view>
              </view>
              <view class="rating-container">
                <u-rate
                  :value="item.score || 0"
                  :count="5"
                  :size="24"
                  active-color="#ff9500"
                  inactive-color="#e4e7ed"
                  :readonly="true"
                ></u-rate>
              </view>
            </view>

            <!-- 商品信息卡片 -->
            <view class="product-card">
              <image class="product-image" :src="item.pic" mode="aspectFill"></image>
              <view class="product-name">{{ item.prodName || '-' }}</view>
            </view>

            <!-- 评价内容 -->
            <view class="review-content" v-if="item.content">
              <text class="content-text">{{ item.content }}</text>
            </view>
            <view class="no-content" v-else>
              <text class="no-content-text">用户未填写评价内容</text>
            </view>
          </view>

          <!-- 加载状态 -->
          <view class="load-status">
            <view class="load-more" v-if="hasMoreComments">
              <text class="load-text">{{ loadingComments ? '加载中...' : '上拉加载更多评价' }}</text>
            </view>
            <view class="no-more" v-else>
              <text class="no-more-text">没有更多评价了</text>
            </view>
          </view>
        </block>

        <!-- 空状态 -->
        <view class="empty-state" v-else>
          <view class="empty-icon">💬</view>
          <text class="empty-title">暂无评价</text>
          <text class="empty-desc">还没有用户评价这家店铺</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shopId: '',
      shopInfo: {},
      shopCardId: "",//店铺cardId
      tabs: [{name: '商品'}, {name: '评价'}],
      activeTab: 0,
      goodsList: [],
      pageNo: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      commList: [],// 评价列表
      commPageNo: 1, // 评价页码
      commPageSize: 10, // 评价每页大小
      hasMoreComments: true, // 是否有更多评价
      loadingComments: false, // 评价加载状态
    }
  },
  onLoad(opt) {
    this.shopId = opt.shopId ? opt.shopId : ''
    this.shopCardId = opt.shopCardId ? opt.shopCardId : ''
    if (opt.shopCardId) {
      this._getInfoByCard(opt.shopCardId)
      this._getMssdsProdCommList(opt.shopCardId)
    }
    if (this.shopId) {
      this._getInfo()
    }
    if (!this.shopCardId && !this.shopId) {
      uni.navigateBack({delta: 1})
    }

  },
  methods: {
    // 根据cardId获取店铺的评价列表
    _getMssdsProdCommList(id, isLoadMore = false) {
      if (this.loadingComments) return

      this.loadingComments = true
      const params = {
        cardId: id,
        pageNo: isLoadMore ? this.commPageNo : 1,
        pageSize: this.commPageSize
      }

      if (!isLoadMore) {
        this.commPageNo = 1
        this.hasMoreComments = true
        this.commList = []
      }

      this.$api.getMssdsProdCommList(params).then((res) => {
        if (res.success && res.result) {
          const newList = res.result.records || []
          this.commList = isLoadMore ? [...this.commList, ...newList] : newList

          const total = res.result.total || 0
          this.hasMoreComments = this.commList.length < total
        } else {
          if (!isLoadMore) {
            this.commList = []
          }
        }
      }).catch(error => {
        console.error('获取评价列表失败:', error)
        if (!isLoadMore) {
          this.commList = []
        }
      }).finally(() => {
        this.loadingComments = false
      })
    },
    // 根据cardId获取店铺基本信息
    _getInfoByCard(id) {
      const params = {cardId: id}
      this.$api.getShopInfoByCard(params).then((res) => {
        if (res.success && res.result) {
          this.shopInfo = res.result
          // 拿到店铺 cardId，拉取商品
          this.resetAndLoadGoods()
        } else {
          this.shopInfo = {}
        }
      })

    },
    //
    // 根据id获取店铺基本信息
    _getInfo() {
      const params = {id: this.shopId}
      this.$api.getMssdShopDetail(params).then((res) => {
        if (res.success && res.result) {
          this.shopInfo = res.result
          // 拿到店铺 cardId，拉取商品
          this.resetAndLoadGoods()
          //   根据店铺cardId，获取评价
          this._getMssdsProdCommList(this.shopInfo.cardId)
        } else {
          this.shopInfo = {}
        }
      })
    },
    // Tab 切换
    onTabChange(e) {
      this.activeTab = e.index || 0
    },
    // 滚动触底
    onReachListBottom() {
      if (this.activeTab === 0) {
        // 商品列表
        if (!this.hasMore || this.loading) return
        this.pageNo += 1
        this.loadGoods()
      } else if (this.activeTab === 1) {
        // 评价列表
        if (!this.hasMoreComments || this.loadingComments) return
        this.commPageNo += 1
        this._getMssdsProdCommList(this.shopInfo.cardId || this.shopCardId, true)
      }
    },
    // 重置并加载商品
    resetAndLoadGoods() {
      this.pageNo = 1
      this.hasMore = true
      this.goodsList = []
      this.loadGoods()
    },
    // 加载商品列表（上架商品）
    async loadGoods() {
      if (!this.shopInfo || !this.shopInfo.cardId) return
      if (this.loading) return
      this.loading = true
      try {
        const params = {
          cardId: this.shopInfo.cardId,
          status: 1,
          pageNo: this.pageNo,
          pageSize: this.pageSize
        }
        const res = await this.$api.getProdShopPage(params)
        if (res && res.success && res.result) {
          const list = res.result.records || []
          this.goodsList = this.pageNo === 1 ? list : [...this.goodsList, ...list]
          const total = res.result.total || 0
          this.hasMore = this.goodsList.length < total
        }
      } catch (e) {
        // ignore
      } finally {
        this.loading = false
      }
    },
    // 进入商品详情（预留）
    goGoodsDetail(item) {
      uni.navigateTo({
        url: `/pagesMall/mallCenter/mallCenterDetail?id=${item.id}&openId=${item.openId}`
      })
      // 可跳转到商品详情页
      // uni.navigateTo({ url: `/pagesMall/goods/detail?id=${item.id}` })
    },
    // 拨打电话
    callPhone() {
      if (!this.shopInfo.tel) {
        return uni.showToast({
          title: '暂无联系电话',
          icon: 'none'
        })
      }
      uni.makePhoneCall({
        phoneNumber: this.shopInfo.tel
      })
    },
    // 地图导航
    goToMap() {
      console.log(this.shopInfo.coord, '导航信息')
      if (!this.shopInfo.coord) {
        return uni.showToast({
          title: '商家没有设置店铺地址',
          icon: 'none'
        })
      }
      try {
        const coordData = JSON.parse(this.shopInfo.coord)
        const {latitude, longitude, name, address} = coordData
        if (latitude && longitude) {
          uni.openLocation({
            latitude: Number(latitude),
            longitude: Number(longitude),
            name: name || this.shopInfo.shopName || '',
            address: address || this.shopInfo.shopAddress || '',
            success: function () {
              console.log('导航成功')
            }
          })
        } else {
          uni.showToast({
            title: '地址数据有误',
            icon: 'none'
          })
        }
      } catch (e) {
        uni.showToast({
          title: '地址数据格式错误',
          icon: 'none'
      })
    }
  },

    // 工具：价格格式化
    formatPrice(val) {
      if (val === null || val === undefined || val === '') return '0.00'
      const num = Number(val)
      if (Number.isNaN(num)) return '0.00'
      return num.toFixed(2)
    },

    // 工具：评价时间格式化
    formatReviewTime(createTime) {
      if (!createTime) return ''

      try {
        // 处理可能的日期格式
        let date
        if (createTime.includes('-') && createTime.length === 10) {
          // 如果是 "2025-09-22" 格式，直接返回
          return createTime
        } else {
          // 其他格式尝试解析
          date = new Date(createTime)
          if (isNaN(date.getTime())) {
            return createTime
          }

          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          return `${year}-${month}-${day}`
        }
      } catch (error) {
        console.error('时间格式化错误:', error)
        return createTime
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-page {
  //min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.shop-header {
  display: flex;
  padding: 30rpx;
  background: linear-gradient(135deg, #4a90e2 0%, #5ba0f2 100%);
  color: #fff;
  gap: 24rpx;
  position: relative;
  overflow: hidden;
}

.shop-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10rpx);
}

.shop-header.placeholder {
  height: 240rpx;
  background: #f5f7fa;
}

.shop-cover {
  position: relative;
  z-index: 1;
}

.shop-logo {
  width: 140rpx;
  height: 140rpx;
  border-radius: 20rpx;
  background-color: #f0f2f5;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.shop-status {
  //position: absolute;
  //top: -8rpx;
  //right: -8rpx;
  background: #67c23a;
  border-radius: 20rpx;
  padding: 4rpx 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-text {
  font-size: 20rpx;
  color: #fff;
  font-weight: 600;
}

.shop-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  position: relative;
  z-index: 1;
}

.shop-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.shop-name {
  font-size: 36rpx;
  font-weight: 700;
  color: #fff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.shop-rating {
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.rating-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 600;
}

.shop-info-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 8rpx 0;
}

.info-text {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  flex: 1;
}

.shop-intro {
  margin-top: 8rpx;
  padding: 16rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12rpx;
  backdrop-filter: blur(10rpx);
}

.intro-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.5;
}

.tabs-wrap {
  background-color: #fff;
}

.content-scroll {
  height: calc(100vh - 220rpx);
}

.goods-list {
  padding: 20rpx;
}

.goods-item {
  background-color: #fff;
  border-radius: 16rpx;
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.goods-cover {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background-color: #f0f2f5;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #303133;
}

.goods-brief {
  font-size: 24rpx;
  color: #909399;
  margin-top: 6rpx;
}

.goods-meta {
  display: flex;
  gap: 20rpx;
  margin-top: 8rpx;
}

.meta {
  font-size: 24rpx;
  color: #606266;
}

.goods-bottom {
  margin-top: 10rpx;
  display: flex;
  justify-content: space-between;
}

.price {
  font-size: 28rpx;
  font-weight: 600;
  color: #ff6b35;
}

.stock {
  font-size: 24rpx;
  color: #606266;
}

.load-more, .no-more, .empty {
  padding: 40rpx;
  text-align: center;
}

.no-more-text, .empty-text, .load-text {
  font-size: 26rpx;
  color: #909399;
}

/* 评价区域 */
.reviews-wrap {
  padding: 24rpx;
  background: #f8f9fa;
}

/* 评价卡片 */
.review-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
  border: 1rpx solid #f0f2f5;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

/* 评价头部 */
.review-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.user-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  font-size: 24rpx;
  color: #fff;
  font-weight: 600;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.user-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.review-date {
  font-size: 22rpx;
  color: #95a5a6;
}

.rating-container {
  display: flex;
  align-items: center;
}

/* 商品信息卡片 */
.product-card {
  display: flex;
  align-items: center;
  gap: 16rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  border: 1rpx solid #e9ecef;
}

.product-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 12rpx;
  background: #dee2e6;
  flex-shrink: 0;
}

.product-name {
  font-size: 26rpx;
  font-weight: 500;
  color: #495057;
  line-height: 1.4;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 评价内容 */
.review-content {
  margin-bottom: 16rpx;
}

.content-text {
  font-size: 30rpx;
  color: #2c3e50;
  line-height: 1.6;
  letter-spacing: 0.5rpx;
  display: block;
}

.no-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx dashed #dee2e6;
}

.no-content-text {
  font-size: 26rpx;
  color: #adb5bd;
  font-style: italic;
}

/* 加载状态 */
.load-status {
  padding: 40rpx 20rpx;
  display: flex;
  justify-content: center;
}

.load-more, .no-more {
  text-align: center;
}

.load-text, .no-more-text {
  font-size: 26rpx;
  color: #6c757d;
  padding: 16rpx 32rpx;
  background: #f8f9fa;
  border-radius: 50rpx;
  border: 1rpx solid #e9ecef;
}

/* 空状态优化 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #6c757d;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #adb5bd;
  line-height: 1.5;
}
</style>
